package com.gp.ssmplus.base.core.mybatis.entity;


import com.fasterxml.jackson.annotation.JsonIgnore;
import com.gp.ssmplus.base.core.mybatis.EnumConvertInterceptor;
import com.gp.ssmplus.base.core.mybatis.common.utils.FlymeUtils;
import org.apache.ibatis.type.Alias;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 自定义Map
 */
@Alias("EntityMap")
public class EntityMap extends HashMap<String, Object> {

    @JsonIgnore
    public static EnumConvertInterceptor interceptors = null;


    public EntityMap() {

    }

    public EntityMap(Map<String, Object> map) {
        this.putAll(map);
    }


    public static void setEnumConvertInterceptor(EnumConvertInterceptor interceptor) {
        interceptors = interceptor;
    }


    @Override
    public EntityMap put(String key, Object value) {
        super.put(key, Optional.ofNullable(value).orElse(""));
        return this;
    }

    public EntityMap add(String key, Object value) {
        super.put(key, Optional.ofNullable(value).orElse(""));
        return this;
    }

    @SuppressWarnings("unchecked")
    public <T> T get(String key) {
        return (T) super.get(key);
    }

    public Long getLong(String key) {
        Object v = get(key);
        if (FlymeUtils.isNotEmpty(v)) {
            return new Long(v.toString());
        }
        return null;
    }

    public Long[] getLongs(String key) {
        Long[] v = get(key);
        if (FlymeUtils.isNotEmpty(v)) {
            return v;
        }
        return null;
    }

    public Integer getInt(String key) {
        Object v = get(key);
        if (FlymeUtils.isNotEmpty(v)) {
            return Integer.parseInt(v.toString());
        }
        return 0;
    }

    public BigDecimal getBigDecimal(String key) {
        Object v = get(key);
        if (FlymeUtils.isNotEmpty(v)) {
            return new BigDecimal(v.toString());
        }
        return new BigDecimal("0");
    }


    @SuppressWarnings("unchecked")
    public <T> T get(String key, T def) {
        Object obj = super.get(key);
        if (FlymeUtils.isNotEmpty(obj)) {
            return def;
        }
        return (T) obj;
    }

    public static EntityMap castTomap(Object obj) {
        EntityMap map = new EntityMap();
        map.putAll((Map<? extends String, ?>) obj);
        return map;
    }


}
